﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using Autofac;
using ComputerVision.BaseForm;
using ComputerVision.Common;
using ComputerVision.Data;
using ComputerVision.Services;
using RawInput_dll;

namespace ComputerVision
{
    public partial class frmSaoLuu : frmObject
    {
        private string connectionstring = null;
        private SqlConnectionStringBuilder builder;
        SqlConnection connection = null;

        public frmSaoLuu()
        {
            InitializeComponent();
            connectionstring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            builder = new SqlConnectionStringBuilder(connectionstring);
        }

        private void btSaoLuu_Click(object sender, EventArgs e)
        {
            saveFileDialog1.FileName = "Backup_NMSP_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".bak";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;
                string sql = "Backup database ComputerVision to disk='" + saveFileDialog1.FileName + "'";
                if (ExecuteNonQuery(sql) > 0)
                {
                    Cursor.Current = Cursors.Default;
                    AlertList.Information("Sao lưu dữ liệu thành công");
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    AlertList.Error("Sao lưu dữ liệu thất bại. Vui lòng thử lại sau");
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btReset_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn chắc chắn muốn xóa dữ liệu xe vào ra? \nHãy cân nhắc trước khi đồng ý.", @"Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                Cursor.Current = Cursors.WaitCursor;
                string sql = "DELETE FROM [XeTemp]; DELETE FROM [Xe]; ";
                string drop = "DROP TABLE [dbo].[Xe]; " +
                              " SET ANSI_NULLS ON; " +
                              "  SET QUOTED_IDENTIFIER ON; " +
                              " CREATE TABLE [dbo].[Xe]( " +
                              "     [Id] [uniqueidentifier] NOT NULL, " +
                              "    [LoaiXeId] [uniqueidentifier] NOT NULL, " +
                              "     [SoVe] [nchar](10) NOT NULL, " +
                              "     [BienSoXe] [nvarchar](50) NOT NULL, " +
                              "    [NgayVao] [datetime] NULL, " +
                              "    [NgayRa] [datetime] NULL, " +
                              "    [ImgVaoTruoc] [nvarchar](500) NULL, " +
                              "    [ImgVaoSau] [nvarchar](500) NULL, " +
                              "    [ImgRaTruoc] [nvarchar](500) NULL, " +
                              "   [ImgRaSau] [nvarchar](500) NULL, " +
                              "   [ImgBienXeVao] [nvarchar](500) NULL, " +
                              "   [ImgBienXeRa] [nvarchar](500) NULL, " +
                              "   [GiaTien] [money] NULL, " +
                              "   [Status] [bit] NULL, " +
                              "  [Created] [datetime] NOT NULL, " +
                              "   [Modified] [datetime] NOT NULL, " +
                              "   [CreatedBy] [nvarchar](255) NOT NULL, " +
                              "   [ModifiedBy] [nvarchar](255) NOT NULL, " +
                              "   [CardStatus] [nvarchar](255) NULL, " +
                              "  CONSTRAINT [PK_Xe_1] PRIMARY KEY CLUSTERED  " +
                              "  ( " +
                              "     [Id] ASC " +
                              "  )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] " +
                              "  ) ON [PRIMARY];";

                string drop2 = "ALTER TABLE [dbo].[Xe] DROP CONSTRAINT [FK_Xe_VeXe]; " +

                               " ALTER TABLE [dbo].[Xe] DROP CONSTRAINT [FK_Xe_LoaiXe]; " +

                               "  DROP TABLE [dbo].[Xe]; " +

                               "  SET ANSI_NULLS ON; " +

                               "  SET QUOTED_IDENTIFIER ON; " +

                               "  CREATE TABLE [dbo].[Xe]( " +
                                "     [Id] [uniqueidentifier] NOT NULL," +
                                "     [LoaiXeId] [uniqueidentifier] NOT NULL," +
                                 "    [SoVe] [nchar](10) NOT NULL," +
                                  "   [BienSoXe] [nvarchar](50) NOT NULL," +
                                    " [NgayVao] [datetime] NULL," +
                               "      [NgayRa] [datetime] NULL," +
                               "      [ImgVaoTruoc] [nvarchar](500) NULL," +
                               "      [ImgVaoSau] [nvarchar](500) NULL," +
                               "      [ImgRaTruoc] [nvarchar](500) NULL," +
                               "      [ImgRaSau] [nvarchar](500) NULL," +
                                "     [ImgBienXeVao] [nvarchar](500) NULL," +
                                "     [ImgBienXeRa] [nvarchar](500) NULL," +
                                "     [GiaTien] [money] NULL," +
                                "     [Status] [bit] NULL," +
                                "     [Created] [datetime] NOT NULL," +
                                 "    [Modified] [datetime] NOT NULL," +
                                 "    [CreatedBy] [nvarchar](255) NOT NULL," +
                                 "    [ModifiedBy] [nvarchar](255) NOT NULL," +
                                 "    [CardStatus] [nvarchar](255) NULL," +
                              "    CONSTRAINT [PK_Xe_1] PRIMARY KEY CLUSTERED " +
                             "    (" +
                             "        [Id] ASC" +
                             "    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]" +
                             "    ) ON [PRIMARY];" +

                             "    ALTER TABLE [dbo].[Xe]  WITH CHECK ADD  CONSTRAINT [FK_Xe_LoaiXe] FOREIGN KEY([LoaiXeId])" +
                             "    REFERENCES [dbo].[LoaiXe] ([Id]);" +

                             "    ALTER TABLE [dbo].[Xe] CHECK CONSTRAINT [FK_Xe_LoaiXe];" +

                            "     ALTER TABLE [dbo].[Xe]  WITH CHECK ADD  CONSTRAINT [FK_Xe_VeXe] FOREIGN KEY([SoVe])" +
                             "    REFERENCES [dbo].[VeXe] ([SoVe]);" +

                             "    ALTER TABLE [dbo].[Xe] CHECK CONSTRAINT [FK_Xe_VeXe];";

                string droptemp = " ALTER TABLE [dbo].[XeTemp] DROP CONSTRAINT [FK_XeTemp_VeXe]; " +
                                   " ALTER TABLE [dbo].[XeTemp] DROP CONSTRAINT [FK_XeTemp_LoaiXe]; " +
                                   "  DROP TABLE [dbo].[XeTemp]; " +
                                   "  SET ANSI_NULLS ON; " +
                                   "  SET QUOTED_IDENTIFIER ON; " +
                                   "  CREATE TABLE [dbo].[XeTemp]( " +
                                    "     [Id] [uniqueidentifier] NOT NULL, " +
                                    "     [LoaiXeId] [uniqueidentifier] NOT NULL, " +
                                    "     [SoVe] [nchar](10) NOT NULL, " +
                                     "    [BienSoXe] [nvarchar](50) NOT NULL, " +
                                    "     [NgayVao] [datetime] NULL, " +
                                    "     [NgayRa] [datetime] NULL, " +
                                     "    [ImgVaoTruoc] [nvarchar](500) NULL, " +
                                     "    [ImgVaoSau] [nvarchar](500) NULL, " +
                                     "    [ImgRaTruoc] [nvarchar](500) NULL, " +
                                     "    [ImgRaSau] [nvarchar](500) NULL, " +
                                     "    [ImgBienXeVao] [nvarchar](500) NULL, " +
                                     "    [ImgBienXeRa] [nvarchar](500) NULL, " +
                                     "    [GiaTien] [money] NULL, " +
                                     "    [CardStatus] [nvarchar](255) NULL, " +
                                     "    [Status] [bit] NULL, " +
                                     "    [Created] [datetime] NOT NULL, " +
                                     "    [Modified] [datetime] NOT NULL, " +
                                     "    [CreatedBy] [nvarchar](255) NOT NULL, " +
                                     "    [ModifiedBy] [nvarchar](255) NOT NULL, " +
                                    "  CONSTRAINT [PK_XeTemp_1] PRIMARY KEY CLUSTERED  " +
                                   "  ( " +
                                   "      [Id] ASC " +
                                   "  )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] " +
                                   "  ) ON [PRIMARY]; " +

                                   "  ALTER TABLE [dbo].[XeTemp]  WITH CHECK ADD  CONSTRAINT [FK_XeTemp_LoaiXe] FOREIGN KEY([LoaiXeId]) " +
                                   "  REFERENCES [dbo].[LoaiXe] ([Id]); " +

                                   "  ALTER TABLE [dbo].[XeTemp] CHECK CONSTRAINT [FK_XeTemp_LoaiXe]; " +

                                   "  ALTER TABLE [dbo].[XeTemp]  WITH CHECK ADD  CONSTRAINT [FK_XeTemp_VeXe] FOREIGN KEY([SoVe]) " +
                                   "  REFERENCES [dbo].[VeXe] ([SoVe]); " +

                                   "  ALTER TABLE [dbo].[XeTemp] CHECK CONSTRAINT [FK_XeTemp_VeXe];";
                if (ExecuteNonQuery(drop2) > 0)
                {
                    Cursor.Current = Cursors.Default;
                    AlertList.Information("Xóa dữ liệu thành công");
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    AlertList.Error("Gặp lỗi khi xóa dữ liệu. Xin vui lòng thực hiện thao tác này sau.");
                }
            }
        }

        public int ExecuteNonQuery(string inputQuery)
        {
            SqlCommand command = new SqlCommand();
            command.CommandType = CommandType.Text;
            command.CommandText = inputQuery;
            command.CommandTimeout = 0;
            int result = 0;
            try
            {
                Connect(connectionstring, out connection);
                command.Connection = connection;
                command.ExecuteNonQuery();
                result = 1;
                return result;

            }
            catch (Exception e)
            {
                MessageBox.Show("Error:" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return result;
            }
            finally
            {
                if (connection != null && connection.State != ConnectionState.Closed)
                    connection.Close();
            }
        }

        private void Connect(string connect, out SqlConnection connection)
        {
            //connection.Close();
            //string connectString = "server=.;uid=sa; pwd=123456; database=rrc_database;";	
            connection = new SqlConnection(connect);
            try
            {
                connection.Open();
                //return connection;
            }
            catch (Exception e)
            {
                MessageBox.Show("Error:" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //return null;

            }
        }

        private void btKhoiPhuc_Click(object sender, EventArgs e)
        {
            //openFileDialog1.FileName = "Backup_NMSP_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".bak";
            connectionstring = "data source=" + builder.DataSource + ";User ID=" + builder.UserID + ";password=" + builder.Password + ";initial catalog=master;";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;
                string sql = "DROP DATABASE ComputerVision; RESTORE DATABASE ComputerVision FROM DISK = N'" + openFileDialog1.FileName + "' WITH  FILE = 1,  NOUNLOAD,  STATS = 10";
                if (ExecuteNonQuery(sql) > 0)
                {
                    Cursor.Current = Cursors.Default;
                    AlertList.Information("Khôi phục dữ liệu thành công");
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    AlertList.Error("Khôi phục dữ liệu thất bại. Vui lòng thử lại sau");
                }
            }
        }


    }
}